import { asyncRoutes, constantRoutes } from '@/router'

/**
 * 使用meta.roleId确定当前用户是否具有权限
 * @param route
 * @param perms
 */
function hasPermission(perms, route) {
  if (route.meta && route.meta.permission) {
    return perms.some(perm => route.meta.permission.includes(perm))
  } else {
      return true
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param perms
 */
export function filterAsyncRoutes(routes, perms) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(perms, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, perms)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  // 所有有权限的路由
  routes: [],
  // 异步路由
  addRoutes: []
}
// 处理路由数据 添加父级name
const routersArr = (routers)=>{
  for(let v of routers) {
    if (v.children) {
      setFuName(v.children, v)
    }
    function setFuName(chid, v) {
      // 开始处理子级
      for (let k of chid) {
        k.meta.fuName = v.name
        k.meta.fuTitle = v.meta.title
      }
    }
  }
  return routers
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = routersArr(constantRoutes.concat(routes))
  }
}

// const actions = {
//   generateRoutes({ commit }, roles) {
//     return new Promise(resolve => {
//       const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
//       commit('setRoutes', accessedRoutes)
//       resolve(accessedRoutes)
//     })
//   }
// }

const actions = {
  generateRoutes({ commit }, perms) {
    return new Promise(resolve => {
      let accessedRoutes
      if (perms.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, perms)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
